<template>
  <el-dialog title="上传图片" :visible.sync="visible" width="500px" @closed="close">
    <div class="app-page">
      <el-upload
        ref="upload"
        class="avatar-uploader"
        action=""
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="(res, file) => handleChange(res, file, 'image1')"
      >
        <img v-if="temp.image1" ref="image1" :src="temp.image1" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <!-- <el-upload
        ref="upload"
        class="avatar-uploader"
        action=""
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="(res, file) => handleChange(res, file, 'image2')"
      >
        <img v-if="temp.image2" ref="image2" :src="temp.image2" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <el-upload
        ref="upload"
        class="avatar-uploader"
        action=""
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="(res, file) => handleChange(res, file, 'image3')"
      >
        <img v-if="temp.image3" ref="image3" :src="temp.image3" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <el-upload
        ref="upload"
        class="avatar-uploader"
        action=""
        accept=".bmp, .gif, .jpg, .jpeg, .png, image/bmp, image/gif, image/jpg, image/jpeg, image/png"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="(res, file) => handleChange(res, file, 'image4')"
      >
        <img v-if="temp.image4" ref="image4" :src="temp.image4" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload> -->
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 关闭 </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryGoodsDefaultData, queryUploadGoodsImage } from '@/api'
  import { mapGetters } from 'vuex'
  import { imgBaseUrl } from '@/utils/config'

  export default {
    name: 'upload-images',
    data() {
      return {
        visible: false,
        row: {},
        temp: {
          image1: '',
          image2: '',
          image3: '',
          image4: ''
        },
        defaultData: [],
        image1Data: '',
        image2Data: '',
        image3Data: '',
        image4Data: ''
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      async open(row) {
        this.row = row
        this.visible = true

        this.getDefaultData(row)
      },
      // 获取默认图片
      async getDefaultData(temp) {
        const res = await queryGoodsDefaultData({
          goodsId: temp.goodsId
        })
        if (res.data.goodsInfo.imageName) {
          if (res.data.goodsInfo.imageName.split(';').length > 0) {
            const arr = res.data.goodsInfo.imageName.split(';')
            arr.forEach((item, index) => {
              this.temp[`image${index + 1}`] = imgBaseUrl + item
            })

            this.$nextTick(() => {
              this.getDefaultDataBlod()
            })
          }
        }
      },
      // 吧默认数据图片转成 file格式
      getDefaultDataBlod() {
        for (const key in this.temp) {
          if (this.temp[key]) {
            const dom = this.$refs[key]
            const _this = this
            this.getBase64Image(dom, (url) => {
              const data = _this.dataURLtoBlob(url)
              const fileName = _this.temp[key].substring(
                imgBaseUrl.length,
                _this.temp[key].length
              )
              const item = {
                key: key,
                data,
                type: data.type,
                name: fileName
              }
              _this.defaultData.push(item)
            })
          }
        }
      },
      handleChange(res, files, name) {
        this.temp[name] = URL.createObjectURL(res.raw)
        this[`${name}Data`] = res.raw
        this.defaultData.forEach((v) => {
          if (v.key === name) {
            v.data = res.raw
            v.name = res.raw.name
            v.type = res.raw.type
          }
        })
      },
      async success() {
        if (!this.row.goodsId) return
        const files = this.defaultData.map((v) => {
          return new File([v.data], v.name, { type: v.type })
        })
        for (let i = 1; i <= 4 - this.defaultData.length; i++) {
          if (this[`image${i + this.defaultData.length}Data`]) files.push(this[`image${i + this.defaultData.length}Data`])
        }
        const params = new FormData()
        params.append('goodsId', this.row.goodsId)
        files.forEach((v) => {
          params.append('files', v)
        })
        const { status } = await queryUploadGoodsImage(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
          this.close()
        }
      },
      getBase64Image(img, callback) {
        let canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        img.setAttribute('crossOrigin', 'Anonymous')
        img.onload = function() {
          console.log(img.width)
          canvas.width = img.width
          canvas.height = img.height
          ctx.drawImage(img, 0, 0, img.width, img.height)
          const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
          const dataURL = canvas.toDataURL('image/' + ext)
          callback.call(this, dataURL) // 回掉函数获取Base64编码
          canvas = null
          img.onload = null
        }
      },

      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(',')
        var mime = arr[0].match(/:(.*?);/)[1]
        var bstr = atob(arr[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], {
          type: mime
        })
      },
      close() {
        this.visible = false
        this.defaultData = []
        this.row = {}

        this.temp = {
          image1: '',
          image2: '',
          image3: '',
          image4: ''
        }
        this.image1Data = ''
        this.image2Data = ''
        this.image3Data = ''
        this.image4Data = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  justify-content: space-evenly;
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
}
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
}
</style>
